<?php
/**
 * 分类管理类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Category extends Base{
    /**
     * 类型列表
     * search: 入参，input精确查找，时间查找，select状态查找
     * @return \think\response\View
     */
    public function categoryList(){
        $search = search($this->params,['category_name']);
        $where  = $search['where'] ?: '';
        $list   = $this->getList($this->category, $where);
        if(!$this->params) $list = infinite($list);  // 检索的话不递归

        foreach ($list as $k=>$v) {
            $list[$k]['topid'] = 0;
            if ($v['pid'] != 0) {
                $list[$k]['topid'] = infiniteTop($list, $v['pid']);
            }
        }
        $count = count($list);
        return view('categoryList',['list'=>$list,'count'=>$count,'params'=>$search['params']]);
    }

    /**
     * 修改分类
     * @return array|\think\response\View
     */
    public function categorySave(){
        $info = !empty($this->params['id']) ? $this->getRow($this->category, $this->params['id']) : [
            'id'            => '',
            'pid'           => '0',
            'category_name' => '',
            'status'        => \Param::STATUS_ON,
        ];
        if(IS_POST){
            try{
                if (!empty($this->params['id'])) {
                    $validate = self::validate($this->params,'Category.save');  // 场景验证
                    if(true !== $validate) throw new \LogicException($validate, -1);

                    $result = compare($this->params, $info);  //参数对比
                    if(!$result) return _success();

                    $num = $this->getCount($this->category, ['pid'=>$info['id']]);
                    if($info['pid'] == 0 && $num > 0 && !empty($this->params['pid'])) throw new \LogicException('该顶级分类下有子分类', -1);

                    $row = $this->category->update($this->params);  // 修改权限
                    if(!$row) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['修改分类', \Param::LOG_TYPE_EDIT ,"修改“ID：{$info['id']}”分类{$result}"];
                } else {
                    $validate = self::validate($this->params,'Category.save');  // 场景验证
                    if(true !== $validate) throw new \LogicException($validate, -1);

                    $id = $this->category->insertGetId($this->params);  // 添加权限
                    if(!$id) throw new \LogicException('操作失败', -1);

                    $this->logs[] = ['新增分类', \Param::LOG_TYPE_ADD, "新增“ID：{$id}”分类“{$this->params['category_name']}”"];
                }
            }catch(\Exception $e){
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }

        // 获取已启用分类列表
        $list = $this->getList($this->category, ['status'=>\Param::STATUS_ON]);
        $list = infinite($list);

        return view('categorySave',['list'=>$list,'info'=>$info]);
    }

    /**
     * 修改状态
     * @return array
     */
    public function status(){
        if(IS_POST){
            try{
                $info = $this->getRow($this->category, $this->params['id']);
                if(!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该分类不存在', -1);

                $row = $this->category->update(['id'=>$this->params['id'],'status'=>$this->params['status']]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $status = $this->params['status'] == \Param::STATUS_ON ? '已启用' : '已禁用';

                $this->logs[] = ['修改分类', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”分类“{$info['category_name']}”，状态为“{$status}”"];
            } catch(\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }
    }
}